<?php

namespace yak\layui\behaviors;

use Yii;
use yii\base\ActionFilter;
use yii\web\ForbiddenHttpException;
use yii\web\Response;

/**
 * Class AuthFilter
 * @package yak\layui\behaviors
 */
class AuthFilter extends ActionFilter
{
    public function beforeAction($action)
    {
        $user = Yii::$app->getUser();
        if ($user !== null && $user->getIsGuest()) {
            $user->loginRequired();
            return false;
        }

        if ($user->identity->super()) {
            return true;
        }

        if (!$this->canPass()) {

            if (Yii::$app->request->isAjax) {
                $this->returnResult(2, '无权访问');
            }

            throw new ForbiddenHttpException('无权访问');

        }

        if (Yii::$app->request->isAjax && strtoupper($_SERVER['REQUEST_METHOD']) == 'OPTIONS') {
            $this->returnResult(0, 'ok');
        }

        return true;
    }

    private function canPass()
    {
        return Yii::$app->user->can(Yii::$app->controller->route);
    }

    private function returnResult($code, $msg)
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        Yii::$app->response->data = ['code' => $code, 'msg' => $msg];
        Yii::$app->response->send();
        exit();
    }
}